#!/bin/bash

echo "🔥 强制清理所有相关进程..."

# 1. 终止所有占用3000端口的进程
echo "📡 清理端口3000..."
PORT_PIDS=$(lsof -ti:3000)
if [ ! -z "$PORT_PIDS" ]; then
    echo "💀 终止端口3000进程: $PORT_PIDS"
    kill -9 $PORT_PIDS 2>/dev/null || true
fi

# 2. 终止所有NestJS相关进程
echo "🔍 清理NestJS进程..."
pkill -f "nest.js" 2>/dev/null || true
pkill -f "nest start" 2>/dev/null || true
pkill -f "nest start --watch" 2>/dev/null || true

# 3. 终止所有npm start:dev进程
echo "🔍 清理npm进程..."
pkill -f "npm run start:dev" 2>/dev/null || true
pkill -f "npm start:dev" 2>/dev/null || true

# 4. 终止所有node进程（在当前目录的）
echo "🔍 清理当前目录的node进程..."
pkill -f "women-ser" 2>/dev/null || true
pkill -f "text-tags-backend" 2>/dev/null || true

# 5. 清理PM2
echo "🔍 清理PM2..."
pm2 stop all 2>/dev/null || true
pm2 delete all 2>/dev/null || true

# 6. 等待进程完全终止
echo "⏳ 等待进程终止..."
sleep 3

# 7. 最终检查
echo "🔍 最终检查..."
REMAINING=$(lsof -ti:3000)
if [ ! -z "$REMAINING" ]; then
    echo "⚠️  仍有进程占用3000端口: $REMAINING"
    kill -9 $REMAINING 2>/dev/null || true
    sleep 2
fi

# 8. 验证清理结果
FINAL_CHECK=$(lsof -ti:3000)
if [ -z "$FINAL_CHECK" ]; then
    echo "✅ 端口3000已完全释放"
else
    echo "❌ 端口3000仍被占用: $FINAL_CHECK"
fi

echo "🎉 强制清理完成！"
